package server_commands;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;

import server.ServerSocketConnection;
import connection_modul.DatabaseConnection;

public class REGCommand extends Command {
	
	
	public REGCommand(String parameter) {
		setCode(REG_CMD);
		setParameter(parameter);
	}
	
	/**
	 *  Predstaljva izvrsenje registracione komande. U zavisnosti od toga da li korisnik postoji u bazi,
	 *  poruka 
	 */
	public boolean executeCommand(ServerSocketConnection connection, DatabaseConnection dbConnection) {
		
		String username, password, nickname, email, avatar;		
		StringTokenizer tokenizer = new StringTokenizer( getParameter() );
		
		SimpleDateFormat sf = new SimpleDateFormat("dd.MM.yyyy");
		Date registrationDate = GregorianCalendar.getInstance().getTime();
		String date = sf.format(registrationDate);		
		
		username = tokenizer.nextToken().toLowerCase();
		password = tokenizer.nextToken();
		nickname = tokenizer.nextToken();
		email = tokenizer.nextToken();
		avatar = tokenizer.nextToken();
		
		try {
			dbConnection.doStatement("SELECT * FROM tblUsers " +
					"WHERE tblUsers.username = '" + username + "'");
		
		
			if( dbConnection.data.size() != 0 ) {
				connection.setMessage("220 User already registered");
				dbConnection.doCommit();
				return true;
			}
		
			String SQLQuery = "INSERT INTO tblUsers " +
				"VALUES ('" + username + "', '" + password + "', '" + nickname + "', '"
				+ email + "', '0.0.0.0', '0.0.0.0', '0', 'Offline', '" + date + "', '" + avatar + "')";  
			

			dbConnection.doUpdateStatement(SQLQuery);		
		
		} catch (SQLException e) {		
			e.printStackTrace();
			dbConnection.doRollBack();
			return false;
		}
		
		dbConnection.doCommit();
		
		connection.setMessage("100 Registration OK");

		return true;
	}

}
